package com.winai.launcher.service;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.SystemClock;
import android.util.Log;

import com.winai.launcher.service.heartBeat.AbsHeartBeatService;
import com.winai.launcher.utils.ServiceUtils;

/**
 * 作者：康少
 * 时间：2020/4/7 0007
 * 说明：服务帮助类
 */
public class ServiceHolder {
    private static final String TAG = "---> ServiceHolder";
    @SuppressLint("StaticFieldLeak")
    public static Context mContext;
    public static Class<? extends Service> mService;
    private static String mServiceCanonicalName;

    private ServiceHolder() {
    }

    public static void init(Context context, Class<? extends AbsHeartBeatService> service) {
        mContext = context;
        mService = service;
        mServiceCanonicalName = service.getCanonicalName();
        startService();
    }

    public static void startService() {
        if (mContext != null && mService != null && !ServiceUtils.isServiceRunning(mContext, mServiceCanonicalName)) {
            try {
                Intent i = new Intent(mContext, mService);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startService(i);
                Log.d(TAG, "启动服务:" + mService.getName());
            } catch (Exception e) {
                e.printStackTrace();
            }

            mContext.getPackageManager().setComponentEnabledSetting(new ComponentName(mContext.getPackageName(), mService.getName()),
                    PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
        }
    }

    public static void stopService() {
        if (mContext != null && mService != null && ServiceUtils.isServiceRunning(mContext, mServiceCanonicalName)) {
            try {
                mContext.stopService(new Intent(mContext, mService));
                Log.d(TAG, "停止服务:" + mService.getName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void restartService(Context context, Class<?> cls) {
        Log.d(TAG, "重启服务:" + cls.getName());
        Intent intent = new Intent(context, cls);
        intent.setPackage(context.getPackageName());
        PendingIntent pendingIntent = PendingIntent.getService(context, 1, intent, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if (alarmManager != null) {
            alarmManager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + ServiceUtils.getIntervalTime(), pendingIntent);
        }
    }
}
